package com.acme.entity.util;

import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class ChangeSupport {

    private CopyOnWriteArrayList<ChangeListener> listeners = new CopyOnWriteArrayList<ChangeListener>();
    private Object source;

    public ChangeSupport(Object source) {
        this.source = source;
    }

    public void addChangeListener(ChangeListener listener) {
        if( listener != null ) listeners.add(listener);
    }

    public void removeChangeListener(ChangeListener listener) {
        if( listener != null ) listeners.remove(listener);
    }

    public void fireChange() {
        if( hasListeners() ) fireChange( new ChangeEvent(source) );
    }

    private void fireChange(ChangeEvent evt) {
        for (ChangeListener listener : listeners) {
            listener.stateChanged(evt);
        }
    }

    public boolean hasListeners() {
        return !listeners.isEmpty();
    }

}
